Visualización de datos INE en R

Juny 16, 2021 By R on Ignacio Ponsoda & Santiago Mota

Introducción

En esta presentacción vamos a aprender como visualizar datos procedentes del INE de una forma dinámica.

Vamos a utilizar datos por distrito censal correspondientes a las edades de los ciudadanos en Madrid, procedentes del INE.

if(!require("leaflet")) install.packages("leaflet")
## Loading required package: leaflet
if(!require("sf")) install.packages("sf")
## Loading required package: sf
## Linking to GEOS 3.9.0, GDAL 3.2.1, PROJ 7.2.1
if(!require("tmap")) install.packages("tamp")
## Loading required package: tmap
if(!require("tidyverse")) install.packages("tidyverse")
## Loading required package: tidyverse
## -- Attaching packages --------------------------------------- tidyverse 1.3.1 --
## v ggplot2 3.3.3     v purrr   0.3.4
## v tibble  3.1.2     v dplyr   1.0.6
## v tidyr   1.1.3     v stringr 1.4.0
## v readr   1.4.0     v forcats 0.5.1
## -- Conflicts ------------------------------------------ tidyverse_conflicts() --
## x dplyr::filter() masks stats::filter()
## x dplyr::lag()    masks stats::lag()
library(leaflet)
library(sf)
library(tmap)
library(tidyverse)

Descarga de archivos

En primer lugar, vamos a descargar los archivos necesarios para la presentación. En este caso se trata de un shapefile dividido por secciones censales y los datos del último censo (2011) de Madrid en csv.

Para ello, crearemos dos archivos temporales para cada uno, que nos permitan descargar la información y asignarla a una variable.

temp  <- tempfile()
temp2 <- tempfile()
temp3 <- tempfile()

Utilizando estos archivos temporales, descargamos el shapefile (con los temp 1 y 2 y los datos del censo con el temp 3).

Tras descargar el shapefile, utilizamos el read_sf para leer el archivo. Por su lado, para el csv, utilizamos el read.table para poder utilizar los datos.

download.file("https://www.ine.es/censos2011_datos/cartografia_censo2011_nacional.zip", temp)
unzip(zipfile = temp, exdir = temp2)
shp_file <- list.files(temp2, pattern = ".shp$", full.names = TRUE)
censales_shp <- sf::read_sf(shp_file)

download.file("https://www.ine.es/censos2011_datos/indicadores_seccion_censal_csv.zip", temp3)
unzip_temp3 <- unzip(temp3, "C2011_ccaa13_Indicadores.csv")
datos_temp3 <- read.table(unzip_temp3, header = TRUE, sep = ",")

Análisis y filtrado de datos

Vamos a observar las primeras líneas de los dos conjuntos de datos

head(datos_temp3)
##   ccaa cpro cmun dist secc t1_1 t2_1 t2_2 t3_1 t3_2 t3_3 t4_1 t4_2 t4_3 t4_4
## 1   13   28    1    1    1   65   35   30    0   45   20   65   NA   NA   NA
## 2   13   28    2    1    1 2000 1070  930  430 1435  135 1845   40   15   15
## 3   13   28    2    1    2 2085 1065 1020  395 1515  175 1585  195    0    0
## 4   13   28    3    1    1  245  135  105   30  150   65  215   20    0    0
## 5   13   28    4    1    1 2125 1055 1065  530 1370  220 1615  100   20  325
## 6   13   28    4    1    2 3485 1935 1550  780 2275  435 2940  245    0  100
##   t4_5 t4_6 t4_7 t4_8 t5_1 t5_2 t5_3 t5_4 t5_5 t5_6 t5_7 t5_8 t5_9 t5_10 t5_11
## 1   NA   NA   NA   NA   65   NA   NA   NA   NA   NA   NA   NA   NA    NA    NA
## 2   85    0    0    0 1825   25    0   40    0   15   15    0    0    85     0
## 3  305    0    0    0 1550   35    0  195    0    0    0    0   45   260     0
## 4   10    0    0    0  215   NA   NA   NA   NA   NA   NA   NA   NA    NA    NA
## 5   55    0    5    0 1520   95   40   65   10   10    0  325    5    50     0
## 6  200    0    0    0 2915   25   15  230    0    0   10   90  130    65     0
##   t5_12 t5_13 t5_14 t5_15 t5_16 t6_1 t6_2 t7_1 t7_2 t7_3 t7_4 t7_5 t7_6 t8_1
## 1    NA    NA    NA    NA    NA   65    5    0   25   15    0   20   10   35
## 2     0     0     0     0     0 1835  165  215  780   75  215  655   60 1000
## 3     0     0     0     0     0 1595  485  220  785   60  175  725  120  850
## 4    NA    NA    NA    NA    NA  220   25   15   85   35   15   60   30  120
## 5     0     5     0     0     0 1580  545  235  700  120  295  670  100  805
## 6     0     0     0     0     0 3075  410  455 1235  245  320 1040  190 1715
##   t8_2 t8_3 t8_4 t9_1 t9_2 t9_3 t9_4 t9_5 t9_6 t10_1 t10_2 t10_3 t10_4 t10_5
## 1    5   30    0    0    0   40    5   20    0    30    30     0     0    10
## 2   70  835   95  395   30 1305  135  135    0  1010   825    15   105    45
## 3  215  745  275  360   35 1060  455  175    0   945   930     0   145    60
## 4   15   95   10   30    0  125   25   65    0    85   125     5    10    15
## 5  250  770  295  305  225 1065  305  205   15   960  1040    40    25    60
## 6  225 1360  190  755   25 1910  365  410   20  1465  1565    60   220   175
##   t11_1 t11_2 t11_3 t11_4 t11_5 t11_6 t11_7 t11_8 t11_9 t11_10 t11_11 t11_12
## 1    NA    20    NA    NA    20    10    NA    NA    NA     NA     NA     NA
## 2   430   580     0     0   710   120     0    15     0      0    105      0
## 3   395   525    25     0   835   100     0     0     0      0    140      5
## 4    30    55     0     0    75    50     0     5     0      0     10      0
## 5   530   425     5     0   885   155     0    25    15      0     25      0
## 6   780   685     0     0  1270   300     0    55     5      0    205     15
##   t11_13 t11_14 t11_15 t12_1 t12_2 t12_3 t12_4 t12_5 t12_6 t13_1 t13_2 t13_3
## 1     NA     NA     NA     5    10    15    25    10     0    NA    NA    NA
## 2      0     30     20    15    80   185  1015   270   430     5    10    50
## 3      0     10     50    20    60   250  1145   215   395     5    15    15
## 4      0      0     10     0    15    45   120    40    30     0     0    10
## 5      0     15     45    60   160   175   945   250   530    30    30    45
## 6      0     60    120     0   155   335  1810   410   780     0     0   110
##   t13_4 t13_5 t13_6 t13_7 t13_8 t13_9 t13_10 t13_11 t13_12 t14_1 t14_2 t14_3
## 1    NA    10    NA    15    10    NA     NA     NA     NA    NA    NA    10
## 2    30    70   115   640   375    90    180    215    215    15     0    80
## 3    45   130   120   600   540    90    125    220    175    20     0    60
## 4     5    15    25    75    45    20     20     15     15     0     0    15
## 5   115   110    65   505   440   130    115    235    295     0    60   120
## 6    45   230   105   960   845   180    230    455    320     0     0   155
##   t14_4 t14_5 t14_6 t14_7 t14_8 t14_9 t14_10 t14_11 t14_12 t15_2 t15_3 t15_5
## 1    NA    15    NA    25    NA    NA     NA     NA     NA    NA    NA    NA
## 2     0   185     0   910   105   240     30    395     30     0    15    15
## 3     0   135   115   810   335   215      5    360     35     0    20     5
## 4     0    45     0   100    15    30     10     30      0     0     0     5
## 5    40   140    35   820   125   195     50    305    225    60     0    75
## 6     0   270    65  1485   325   410      0    755     25     0     0    20
##   t15_6 t15_8 t15_9 t15_11 t15_12 t15_14 t15_15 t15_16 t16_1 t17_1 t17_2 t17_3
## 1    NA    NA    10     20     NA     10     NA     NA   145    35   105     5
## 2    65   155    35    995     20    270      0    430   725   715     0    10
## 3    55   195    60   1115     30    200     15    395   840   820     5    10
## 4    10    10    30     95     20     40      0     30   395   115   180   100
## 5    85   130    45    890     55    220     30    530  1010   730    50   230
## 6   135   255    85   1610    200    390     20    780  1840  1240   305   295
##   t18_1 t18_2 t18_3 t18_4 t18_5 t18_6 t19_1 t19_2 t19_3 t19_4 t19_5 t19_6 t19_7
## 1    20    NA    NA    NA    NA    NA    NA    NA    NA    NA    10    NA    NA
## 2   180   420    25    55    10    25     0    25    95   120   135    45    55
## 3   230   315     5   240     0    35     0    10   150   145   250   110    50
## 4    40    25    15    15     5    10     0     0    15     5    30    15    10
## 5   135   415    25   120    20    15     0    20    80    95    40    85   110
## 6   305   520    70   235    80    30     0    60   115    70   240   115   135
##   t19_8 t19_9 t19_10 t20_1 t20_2 t20_3 t20_4 t20_5 t20_6 t20_7 t20_8 t20_9
## 1    NA    NA     NA    NA    NA    NA    10    10    NA    NA    NA    NA
## 2    60    70    105    10    35   100   180   185   110    70    30     0
## 3    70    15     25    20    30    75   215   325   125    10    20     0
## 4    15    10     15     0     0    10    25    25    25    15     5    10
## 5   170    90     40    40    15   150   100   110   275    30    10     0
## 6   165    95    250    45    60   170    85   370   295   120    40    55
##   t21_1 t22_1 t22_2 t22_3 t22_4 t22_5 t22_6
## 1    35    15    15    NA    NA    NA    NA
## 2   715   115   225   135   170    55    15
## 3   820   210   290    85   145    95     0
## 4   115    40    35    20    15     0     0
## 5   730    45   305   140   160    45    30
## 6  1240   210   370   275   260   115    15
head(censales_shp)
## Simple feature collection with 6 features and 21 fields
## Geometry type: MULTIPOLYGON
## Dimension:     XY
## Bounding box:  xmin: 496339.8 ymin: 4737085 xmax: 543234.1 ymax: 4768804
## Projected CRS: ETRS89 / UTM zone 30N
## # A tibble: 6 x 22
##   OBJECTID CUSEC    CUMUN CSEC  CDIS  CMUN  CPRO  CCA   CUDIS  OBS   CNUT0 CNUT1
##      <dbl> <chr>    <chr> <chr> <chr> <chr> <chr> <chr> <chr>  <chr> <chr> <chr>
## 1        1 0100101~ 01001 001   01    001   01    16    01001~ <NA>  ES    2    
## 2        2 0100101~ 01001 002   01    001   01    16    01001~ <NA>  ES    2    
## 3        3 0100201~ 01002 001   01    002   01    16    01002~ <NA>  ES    2    
## 4        4 0100201~ 01002 002   01    002   01    16    01002~ <NA>  ES    2    
## 5        5 0100201~ 01002 003   01    002   01    16    01002~ <NA>  ES    2    
## 6        6 0100201~ 01002 004   01    002   01    16    01002~ <NA>  ES    2    
## # ... with 10 more variables: CNUT2 <chr>, CNUT3 <chr>, CLAU2 <chr>,
## #   NPRO <chr>, NCA <chr>, NMUN <chr>, Shape_Leng <dbl>, Shape_area <dbl>,
## #   Shape_len <dbl>, geometry <MULTIPOLYGON [m]>

Y filtramos los datos por el código de municipio. En este caso, el código de municipio de Madrid es el 28079 (utilizaremos 79 para los datos censales ya que hemos cogido los de la ccaa de Madrid directamente).

madrid_shp <- censales_shp[censales_shp$CUMUN == "28079", ]
madrid_data <- datos_temp3[datos_temp3$cmun == 79, ]

Utilizamos leaflet para comprobar que los datos de shapefile son correctos. Para ellos tendremos que cambiar la proyección a WGS84.

madrid_shp <- st_transform(madrid_shp, '+proj=longlat +datum=WGS84')

leaflet(madrid_shp) %>%
  addTiles() %>%
  addPolygons(weight = 0.5)

Unión de los datos

En esta sección realizaremos una unión de los dos conjuntos de datos. Para ello, tenemos que crear un campo en común en ambos conjuntos, en este caso será la combinación de distrito y sección.

Como los datos del shapefile son strings, utilizaremos el as.numeric y una separación de “-” para crear el campo join_code.

madrid_shp <-transform(madrid_shp, join_code = paste(as.numeric(CDIS), as.numeric(CSEC), sep = "-"))
madrid_data <-transform(madrid_data, join_code = paste(dist,secc, sep="-"))
madrid_merged <- merge(madrid_shp,madrid_data, by = "join_code")

Visualización de datos

# Ploteamos el shape con personas menores de 16
tm_shape(madrid_merged) +
  tm_polygons("t3_1")

tmap_mode("view")
## tmap mode set to interactive viewing
# y ahora lo vemos interactivo
tm_shape(madrid_merged) +
  tm_polygons("t3_1")
# pero son número absolutos, y lo que queremos es ver este dato normalizado por la población
madrid_merged["under_16"] <- with(madrid_merged, 
                                  round((t3_1/(t3_1 + t3_2 + t3_3)*100), 2)) 
madrid_merged["16_64"] <- with(madrid_merged, 
                                  round((t3_2/(t3_1 + t3_2 + t3_3)*100), 2))
madrid_merged["over_64"] <- with(madrid_merged, 
                               round((t3_3/(t3_1 + t3_2 + t3_3)*100), 2)) 

tm_shape(madrid_merged)  +
  tm_fill(c("under_16", "over_64"), title = c("Población menor de 16 (%)","Población mayor de 64 (%)"), style = "fixed",
          breaks = c(0, 10, 20, 30, 40, Inf),
          textNA = "Sin valores", 
          colorNA = "white",
          palette = "-viridis",
          id = "join_code", 
          popup.vars=c("Jovenes mayores 16 (%)"= "under_16", "Entre 16 y 64 (%)"="16_64", "Mayores de 64 (%)"="over_64"))

Información de la sesión

sessionInfo()
## R version 4.1.0 (2021-05-18)
## Platform: x86_64-w64-mingw32/x64 (64-bit)
## Running under: Windows 10 x64 (build 19041)
## 
## Matrix products: default
## 
## locale:
## [1] LC_COLLATE=English_United Kingdom.1252 
## [2] LC_CTYPE=English_United Kingdom.1252   
## [3] LC_MONETARY=English_United Kingdom.1252
## [4] LC_NUMERIC=C                           
## [5] LC_TIME=English_United Kingdom.1252    
## 
## attached base packages:
## [1] stats     graphics  grDevices utils     datasets  methods   base     
## 
## other attached packages:
##  [1] forcats_0.5.1   stringr_1.4.0   dplyr_1.0.6     purrr_0.3.4    
##  [5] readr_1.4.0     tidyr_1.1.3     tibble_3.1.2    ggplot2_3.3.3  
##  [9] tidyverse_1.3.1 tmap_3.3-1      sf_0.9-8        leaflet_2.0.4.1
## 
## loaded via a namespace (and not attached):
##  [1] httr_1.4.2              sass_0.4.0              jsonlite_1.7.2         
##  [4] viridisLite_0.4.0       modelr_0.1.8            bslib_0.2.5.1          
##  [7] assertthat_0.2.1        highr_0.9               sp_1.4-5               
## [10] cellranger_1.1.0        yaml_2.2.1              pillar_1.6.1           
## [13] backports_1.2.1         lattice_0.20-44         glue_1.4.2             
## [16] digest_0.6.27           RColorBrewer_1.1-2      rvest_1.0.0            
## [19] colorspace_2.0-1        leaflet.providers_1.9.0 htmltools_0.5.1.1      
## [22] XML_3.99-0.6            pkgconfig_2.0.3         broom_0.7.6            
## [25] raster_3.4-10           haven_2.4.1             stars_0.5-2            
## [28] scales_1.1.1            proxy_0.4-25            generics_0.1.0         
## [31] ellipsis_0.3.2          withr_2.4.2             leafsync_0.1.0         
## [34] cli_2.5.0               readxl_1.3.1            magrittr_2.0.1         
## [37] crayon_1.4.1            evaluate_0.14           fs_1.5.0               
## [40] fansi_0.4.2             xml2_1.3.2              lwgeom_0.2-6           
## [43] class_7.3-19            tools_4.1.0             hms_1.1.0              
## [46] lifecycle_1.0.0         reprex_2.0.0            munsell_0.5.0          
## [49] compiler_4.1.0          jquerylib_0.1.4         e1071_1.7-7            
## [52] rlang_0.4.11            classInt_0.4-3          units_0.7-1            
## [55] grid_4.1.0              tmaptools_3.1-1         rstudioapi_0.13        
## [58] dichromat_2.0-0         htmlwidgets_1.5.3       crosstalk_1.1.1        
## [61] leafem_0.1.6            base64enc_0.1-3         rmarkdown_2.8          
## [64] gtable_0.3.0            codetools_0.2-18        abind_1.4-5            
## [67] DBI_1.1.1               R6_2.5.0                lubridate_1.7.10       
## [70] knitr_1.33              utf8_1.2.1              KernSmooth_2.23-20     
## [73] stringi_1.6.1           parallel_4.1.0          Rcpp_1.0.6             
## [76] vctrs_0.3.8             png_0.1-7               dbplyr_2.1.1           
## [79] tidyselect_1.1.1        xfun_0.23

Licencias de uso

  • Licencia de uso de los datos del INE. Link